package com.atguigu.juc;

import org.springframework.boot.test.context.SpringBootTest;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;



//比较synchronized和ReentrantLock
class Ticcket {
    private int number = 50;

    // synchronized锁版本
    /*public synchronized void sale() {
        if (number > 0) {
            System.out.println(Thread.currentThread().getName() + "卖出第" + (number--) + "张票，还剩" + number + "张");
        }
    }*/

    //ReentrantLock锁版本    （可重复锁+默认悲观锁+非公平锁）
    private final Lock lock = new ReentrantLock(true);

    public void sale() {
        lock.lock();
        try {
            if (number > 0) {
                System.out.println(Thread.currentThread().getName() + "卖出第" + (number--) + "张票，还剩" + number + "张");
                try {
                    TimeUnit.SECONDS.sleep(4);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        } finally {
            lock.unlock();
        }
    }
}

@SpringBootTest
public class ThreadTicketSelling_50 {

    public static void main(String[] args) {
        Ticcket ticcket = new Ticcket();
        new Thread(() -> {
            for (int i = 1; i <= 50; i++) {
                ticcket.sale();
            }
        }, "B").start();
        new Thread(() -> {
            for (int i = 1; i <= 50; i++) {
                ticcket.sale();
            }
        }, "A").start();
    }
}
